package com.shenmazong.serverwebpoem.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 田不平
 * @project server-web-poem
 * @date 2020/3/24 9:02 PM
 * http://www.shenmazong.com
 */

@Configuration
public class MyShiroConfig {

    @Bean("myUserRealm")
    public MyUserRealm getMyUserRealm() {
        return new MyUserRealm();
    }

    @Bean
    public MyCredentialsMatcher getMyCredentialsMatcher() {
        return new MyCredentialsMatcher();
    }

    @Bean("mySecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager() {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        // 关联realm
        MyUserRealm realm = getMyUserRealm();
        realm.setCredentialsMatcher(getMyCredentialsMatcher());
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
        //--1 设置安全管理器
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());

        //--2 添加Shiro内置过滤器
        /**
         * Shiro内置过滤器，可以实现权限相关的拦截器
         *    常用的过滤器：
         *       anon: 无需认证（登录）可以访问
         *       authc: 必须认证才可以访问
         *       user: 如果使用rememberMe的功能可以直接访问
         *       perms： 该资源必须得到资源权限才可以访问
         *       role: 该资源必须得到角色权限才可以访问
         */
        Map<String,String> filterMap = new LinkedHashMap<String,String>();
        //-- 放行登录页面
        filterMap.put("/login", "anon");
        filterMap.put("/logout", "anon");
        filterMap.put("/doLogin", "anon");

        //-- 设置登录相关url
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setSuccessUrl("/index");

        //-- 设置注销url
        LogoutFilter logout = new LogoutFilter();
        logout.setRedirectUrl("/logout");
        Map<String, Filter> filters=new HashMap<>();
        filters.put("logout", logout);
        shiroFilterFactoryBean.setFilters(filters);
        //filterMap.put("/logout", "logout");

        //-- 设置权限
        filterMap.put("/goNote/**", "authc");
        filterMap.put("/goTranslate/**", "authc");
        filterMap.put("/goAppreciation/**", "authc");
        filterMap.put("/goStory/**", "authc");

        //-- 其他页面无需验证
        filterMap.put("/**", "anon");


        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }
}
